package com.TanNgee.netty.kyro.codec;

import com.TanNgee.netty.kyro.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.AllArgsConstructor;

/**
 * @author 陈毅
 * @create 2022/3/11 0:54
 */

/**
 * 自定义Netty 编码器
 */
@AllArgsConstructor
public class NettyKryoEncoder extends MessageToByteEncoder<Object> {
    private final Serializer serializer;
    private final Class<?> genericClass;

    /**
     * 编码 Object对象为byteBuf数组
     *
     * @param channelHandlerContext
     * @param o
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        // 1.将对象转换为byte数组
        final byte[] body = serializer.serialize(o);
        // 2. 读取消息的长度
        int dataLength = body.length;
        // 3. 写入消息对应的字节数组长度，writerIndex加4
        byteBuf.writeInt(dataLength);
        // 4. 将字节数组写入 ByteBuf对象中
        byteBuf.writeBytes(body);
    }
}
